package com.fz.us.oa.core.service.common.impl;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PagePaging;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.dao.BaseDao;
import com.fz.us.admin.base.service.impl.BaseServiceImpl;
import com.fz.us.oa.core.dao.common.FileManagerDao;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service实现类 - 附件文件
 * ============================================================================
 * 版权所有 2014 。
 *
 * @author min_xu
 *
 * @version 0.1 2014-01-20
 */

@Service
public class FileManagerServiceImpl extends BaseServiceImpl<FileManage, String> implements FileManagerService {

    @Resource
    private FileManagerDao fileManageDao;
    @Resource
    private GridFsTemplate gridOperations;

    @Override
    public BaseDao<FileManage, String> getBaseDao() {
        return fileManageDao;
    }

    /**
     * 从MongoDB中返回对应的文件
     * @param id    MongoDB中文件的主键：_id
     * @return
     */
    public GridFSDBFile gridFSGet(String id) {
        Assert.notNull(id, "grid id is null");
        return gridOperations.findOne(new Query(Criteria.where("_id").is(
                new ObjectId(id))));
    }

    /**
     * 分页
     *
     * @param page
     * @param order
     * @return
     */
    public SearchResultPaging pagingFile(PagePaging page, List<Rule> rules, Order order, BaseEnumManager.StateEnum... states) {
        //Assert.notNull(company, "company is required");

		/*if (rules == null)
			rules = new ArrayList<Rule>();
		rules.add(RuleHelper.eq("company", company));*/

		/*if (states != null && states.length > 0) {
			rules.add(RuleHelper.in("state", states));
		}*/

        // 默认排序
	/*	if (order == null)
			order = Order.order("sortNo", SearchEnum.OrderType.asc);*/

        return findPagingBySearch(page, rules, order);
    }

    /**
     * 列表 Map
     *
     * @return {id:fileManage.id , name:fileManage.name}
     */
    public Map<String, Object> getListMap(FileManage fileManage) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", StringUtils.isEmpty(fileManage.getId())?"":fileManage.getId());
        map.put("name", StringUtils.isEmpty(fileManage.getName())?"":fileManage.getName());

        return map;
    }

    @Override
    public FileManage gridFSSave(InputStream inputStream, String contentType, String filename) throws IOException {
        DBObject metaData = new BasicDBObject();
        metaData.put("filename", filename);
        metaData.put("contentType", contentType);

        GridFSFile file = gridOperations.store(inputStream, filename, contentType, metaData);
        String gridId = file.getId().toString();

        FileManage fileManage = new FileManage();
        fileManage.setUrl("gridId="+gridId);
        fileManage.setGridId(gridId);
        fileManage.setName(filename);
        fileManage.setSize(file.getLength());

        fileManage.setState(BaseEnumManager.StateEnum.Enable);
        save(fileManage);

        metaData.put("fileId", fileManage.getId());
        file.save();

        return fileManage;
    }

    @Override
    public FileManage gridFSSave(File file, String contentType, String filename) throws IOException {
        DBObject metaData = new BasicDBObject();
        
        metaData.put("filename", filename);
        metaData.put("contentType", contentType);
        
        GridFSFile gFile = gridOperations.store(new FileInputStream(file), filename, contentType, metaData);
        String gridId = gFile.getId().toString();

        FileManage fileManage = new FileManage();
        fileManage.setUrl("gridId="+gridId);
        fileManage.setGridId(gridId);
        fileManage.setName(filename);
        fileManage.setSize(gFile.getLength());

        fileManage.setState(BaseEnumManager.StateEnum.Enable);
        save(fileManage);

        metaData.put("fileId", fileManage.getId());
        gFile.save();
        file.delete();

        return fileManage;
    }

    @Override
    public void gridFSDelete(FileManage fileManage){
        fileManage.setState(BaseEnumManager.StateEnum.Delete);
        update(fileManage);

        String gridId = fileManage.getGridId();
        if (StringUtils.isNotEmpty(gridId)) {
            gridOperations.delete(new Query(Criteria.where("_id").is(
                    new ObjectId(gridId))));
        }
    }

    @Override
    public void delete(FileManage entity){
        gridOperations.delete(new Query(Criteria.where("_id").is(new ObjectId(entity.getGridId()))));
        fileManageDao.delete(entity);
    }
}